package zut.wework.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import zut.wework.entity.Student;
import zut.wework.utils.HttpClientUtil;
import zut.wework.utils.JsonUtil;
import zut.wework.utils.RedisUtil;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Classname: CanvasAPI
 * @Description: canvas平台的学生获取
 * @Date: 2022/5/11
 * @Created: by ifaxcaeles
 */
@Slf4j
@Component
public class CanvasAPI {
    public static String GET_STUDENT_API = "https://weapps.zut.edu.cn/canvas_lti/api/courses/%s/sections/%s";//courseId课程id sectionId班级id，如果传入0，则获取全部学生
    public static String GET_COURSE_API = "https://weapps.zut.edu.cn/canvas_lti/api/courses/%s";//courseId课程id
    public static String GET_TEACHER_API = "https://weapps.zut.edu.cn/canvas_lti/api/user/courses/%s/tch";//authId职工号
    public static String GET_TOKEN_API = "https://weapps.zut.edu.cn/canvas_lti/api/token";

    @Value("${app.canvas.username}")
    private String username;

    @Value("${app.canvas.password}")
    private String password;

    @Autowired
    private RedisUtil redisUtil;

    private static final RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(30 * 1000)   //设置连接超时时间
            .setConnectionRequestTimeout(30 * 1000) // 设置请求超时时间
            .setSocketTimeout(30 * 1000)
            .setRedirectsEnabled(true)//默认允许自动重定向
            .build();

    public static final String TOKEN_REDIS = "canvas_token";

    public String getToken() {
        String at;
        if (!(at = String.valueOf(redisUtil.get(TOKEN_REDIS))).equals("null")) {
            log.info("从redis中获取到token:{}", at);
            return at;
        }
        int i = 0;
        HashMap<String, String> params = new HashMap<>();
        params.put("name", username);
        params.put("passWord", password);
        Map<String, Object> mapData = null;
        while (i < 3) {
            String res = HttpClientUtil.post(GET_TOKEN_API, JsonUtil.toJson(params));
            mapData = JsonUtil.toMap(res);
            at = String.valueOf(mapData.get("data"));
            Integer code = (Integer) mapData.get("code");
            if (at != null && code == 200) {
                log.info("获取AccessToken成功:{}", at);
                redisUtil.set(TOKEN_REDIS, at, 1l, TimeUnit.DAYS);
                return at;
            }
            log.info("第{}次获取AccessToken失败", i + 1);
            i++;
        }
        log.error("获取AccessToken失败！！！");
        return null;
    }

    /**
     * @param courseId
     * @return
     * @Description 获取学生列表
     */
    public List<Student> getStudents(String courseId) {
        String token = getToken();
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(String.format(GET_STUDENT_API, courseId, 0));
        request.addHeader("token", token);
        request.setConfig(requestConfig);
        HttpResponse resp;
        List<Student> students = null;
        Map<String, Object> map = new HashMap<>();
        try {
            resp = client.execute(request);
            if (resp != null) {
                HttpEntity entity = resp.getEntity();
                if (entity != null) {
                    map = JsonUtil.toMap(EntityUtils.toString(resp.getEntity()));
                }
            }
            students = new ArrayList<>();
            String data = String.valueOf(map.get("data"));
            JSONArray jsonArray = JSONArray.parseArray(data);
            for (Iterator it = jsonArray.iterator(); it.hasNext(); ) {
                Student student = parseStudent((JSONObject) it.next());
                students.add(student);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return students;
    }

    public static Student parseStudent(Map<String, Object> data) {
        Student student = Student.builder()
                .id(String.valueOf(data.get("id")))
                .courseId(String.valueOf(data.get("courseId")))
                .name(String.valueOf(data.get("name")))
                .userId(String.valueOf(data.get("userId")))
                .courseSectionId(String.valueOf(data.get("courseSectionId")))
                .jxbj(String.valueOf(data.get("jxbj")))
                .zgh(String.valueOf(data.get("zgh")))
                .xb(String.valueOf(data.get("xb")))
                .dwmc(String.valueOf(data.get("dwmc")))
                .zymc(String.valueOf(data.get("zymc")))
                .xzbj(String.valueOf(data.get("xzbj")))
                .build();
        return student;
    }
}